/*
 * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.security.core.context;

import org.springframework.util.Assert;

/**
 * @author Dillon
 * @date 2024/6/28
 * @slogan 致敬大师 致敬未来的你
 * @desc springSecurity 登录成功全局缓存策略
 * 缓存后，所有线程可访问
 */
final class GlobalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {

	/**
	 * SecurityContext 实现类
	 */
	private static SecurityContext contextHolder;

	/**
	 * 清除 SecurityContext 缓存
	 */
	@Override
	public void clearContext() {
		contextHolder = null;
	}

	/**
	 * 获取 SecurityContext 缓存
	 * 如果缓存为空 创建一个空的 SecurityContext
	 * @return SecurityContext
	 */
	@Override
	public SecurityContext getContext() {
		if (contextHolder == null) {
			contextHolder = new SecurityContextImpl();
		}
		return contextHolder;
	}

	/**
	 * 设置  SecurityContext
	 * @param context SecurityContext
	 */
	@Override
	public void setContext(SecurityContext context) {
		Assert.notNull(context, "只允许非空的 SecurityContext 实例");
		contextHolder = context;
	}

	/**
	 * 创建 SecurityContext 默认实现 SecurityContextImpl
	 * @return SecurityContextImpl
	 */
	@Override
	public SecurityContext createEmptyContext() {
		return new SecurityContextImpl();
	}

}
